/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.una.accidentmanagement.bo;

import br.com.una.accidentmanagement.model.ActionTicket;
import br.com.una.accidentmanagement.model.Requester;
import br.com.una.accidentmanagement.util.DatabaseConnection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.TypedQuery;

/**
 *
 * @author santosmgbh
 */
public class LoginController {
    
    private static Requester getLoggedRequester;
    
    public static Requester getLoggedRequester(){
        return getLoggedRequester;
    }
    
    public void addNewUser(Requester requester){
        EntityManager em = DatabaseConnection.instance().getManager();                        
        EntityTransaction et = em.getTransaction();
        et.begin();        
        String newPass = requester.getPasswordHash().hashCode()+"";
        requester.setPasswordHash(newPass);
        em.persist(requester);
        et.commit();
    }
    
    public Boolean isLoginAccepted(String user, String pass){        
        String hashPass = pass.hashCode()+"";
        List<Requester> requesters = getAllRequesters();
        for(Requester r: requesters){
            if(r.getUsername().equalsIgnoreCase(user) && r.getPasswordHash().equals(hashPass)){
                getLoggedRequester = r;
                return true;
            }
        }
        return false;
    }
    public Boolean exists(String user){
        List<Requester> requesters = getAllRequesters();
        for(Requester r: requesters){
            if(r.getUsername().equalsIgnoreCase(user)){
                return true;
            }
        }  
        return false;
    }
    
    public List<Requester> getAllRequesters(){
        EntityManager em = DatabaseConnection.instance().getManager();
        TypedQuery<Requester> query = em.createQuery("SELECT r FROM Requester r", Requester.class);        
        return query.getResultList();
    }
    
}
